package com.atguigu.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;

/**
 * 七牛云工具类
 */
public class QiniuUtil {
    /**
     * accessKey = "y1rFqZqWOTcl-v1KZ2k3EVKt8Pn-QuGB9S18G07K"
     * secretKey = "ax3aPIe-Hx0gueWDOeDjWVM7s55WmUyTT1WYeow4"
     */
    //public  static String accessKey = "BrrMVEQCE6ijrnHX-gGDVVk3e0vY8mAQQEyB_Zzq";
    //public  static String secretKey = "uaJNMOUGSkZqb3xce-gv4Y-2f0f5_X5VQO-v4lL0";
    public static String accessKey = "y1rFqZqWOTcl-v1KZ2k3EVKt8Pn-QuGB9S18G07K";
    public static String secretKey = "ax3aPIe-Hx0gueWDOeDjWVM7s55WmUyTT1WYeow4";
    public static String bucket = "shfang";

    private static Configuration cfg;
    private static UploadManager uploadManager;

    /**
     * 静态代码块抽取代码
     */
    static {
        cfg = new Configuration(Zone.zone1());
        uploadManager = new UploadManager(cfg);
    }

    /**
     * 文件上传,直接指定文件的路径和文件名
     *
     * @param filePath
     * @param fileName
     */
    public static void upload2Qiniu(String filePath, String fileName) {
        //构造一个带指定Zone对象的配置类
        //Configuration cfg = new Configuration(Zone.zone1());
        //UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(filePath, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException ex) {
            Response r = ex.response;
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    /**
     * 字节数组上传,将内存中的字节数组上传到空间中
     *
     * @param bytes
     * @param fileName
     */
    public static String upload2Qiniu(byte[] bytes, String fileName) {
        //构造一个带指定Zone对象的配置类
        //Configuration cfg = new Configuration(Zone.zone1());
        //...其他参数参考类注释
        //UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
            return null;
        }
    }

    /**
     * 在七牛云中删除指定文件
     * "key":"qiniu.jpg" key是文件名.后缀,防止出现文件名相同,但是后缀不同的情况
     * 比如 "qiniu.jpg" 和 "qiniu.bmp",利用文件名删,会两个都删除,使用 文件名.后缀 的格式,可以确保文件的唯一性
     *
     * @param fileName
     */
    public static Boolean deleteFileFromQiniuByKey(String fileName) {
        //构造一个带指定Zone对象的配置类
        //Configuration cfg = new Configuration(Zone.zone1());
        String key = fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
            return true;
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
            return false;
        }
    }

    /**
     * "key":"qiniu.jpg" key是文件名.后缀
     *
     * @param imageUrl
     * @return
     */
    public static Boolean deleteFileFromQiniuByUrl(String imageUrl) {
        String key = getKeyFromUrl(imageUrl);
        Boolean b = deleteFileFromQiniuByKey(key);
        return b;
    }

    /**
     * 查询该文件在七牛云中是否存在
     *
     * @param key
     * @return
     */
    public static Boolean existsByKey(String key) {
        //构造一个带指定Zone对象的配置类
        //Configuration cfg = new Configuration(Zone.zone1());
        if (key == null || key.isEmpty()) {
            return false;
        }
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            FileInfo fileInfo = bucketManager.stat(bucket, key);
            String hash = fileInfo.hash;
            if (null == hash || hash.isEmpty()) {
                return false;
            }
        } catch (QiniuException ex) {
            System.err.println(ex.response.toString());
            return false;
        }
        return true;
    }

    /**
     * 通过url判断该文件在七牛云中是否存在
     * @param url
     * @return
     */
    public static Boolean existsByUrl(String url) {
        String key = getKeyFromUrl(url);
        Boolean b = existsByKey(key);
        return b;
    }

    /**
     * 从url中获取七牛云文件的key,如果有多层目录,则key中包含多层目录名
     * 连接 http://scfvqarb1.hb-bkt.clouddn.com/house/a274e8ff-f6a8-4059-af11-5733951b9f4c
     * @return
     */
    public static String getKeyFromUrl(String url) {
        if (url == null || url.isEmpty()) {
            return null;
        }
        String tempString = url.substring(url.lastIndexOf("//") + 2);
        String key = tempString.substring(tempString.indexOf("/") + 1);
        return key;
    }
}
